// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
import App from './App'
import router from './router'
import ElementUI from 'element-ui'
import server from '../config/api'
import 'element-ui/lib/theme-default/index.css'   // 默认主题

Vue.use(Vuex);
Vue.use(ElementUI)
Vue.config.productionTip = false
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
Vue.prototype.$http = axios;
Vue.prototype.ApiServer = server;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
const store = new Vuex.Store({
      state: {
           isLogin: false,
           user: {},
           access_token: ''
      },
      mutations: {
            setAccessToken(state, access_token) {
                  state.access_token = access_token;
            },
            login(state) {
                  state.isLogin = true;
            },
            logout(state) {
                  state.isLogin = false;
                  state.user = {};
                  state.access_token = '';
            },
            setUser(state, user) {
                  state.user = user;
            }
      }
})

//全局导航钩子
router.beforeEach((to, from, next) => {
    //判断该路由是否需要登录权限
    if (to.meta.requiresAuth) {
        //判断全局状态
        if (!store.state.isLogin) {
            //存在token
            if (localStorage.access_token) {
                //自动登录
                store.commit('setAccessToken', localStorage.access_token);
                store.commit('login');
                // 获取用户信息
                axios.get(server.api.user, {
                    headers: {
                        'Authorization': 'Bearer' + store.state.access_token
                    }
                }).then((response) => {
                    store.commit('setUser', response.body.data);
                }, (error) => {
                    next({
                        path: '/login',
                    })
                });
                next();
            } else {
                next({
                    path: '/login',
                    query: {redirect: to.fullPath}  // 将跳转的路由path作为参数，登录成功后跳转到该路由
                })
            }
        } else {
            next();
        }
    } else {
        next();
    }
})
/* eslint-disable no-new */
new Vue({
      store, //把 store 的实例注入所有的子组件
      router,
      render: h => h(App)
}).$mount('#app')
